package com.tyun.modules.sys.controller;

import com.tyun.common.oss.QiniuCloudStorageService;
import com.tyun.common.utils.BaseUtil;
import com.tyun.common.utils.R;
import com.tyun.common.utils.ThumbnailsUtil;
import com.tyun.modules.sys.properties.Pro;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件上传
 * @author taocongcong
 * @create 2018-06-08 15:51
 */
@RestController
public class FileController {

    @Autowired
    private Pro pro;
    @Autowired
    private QiniuCloudStorageService qiniuCloudStorageService;

    @RequestMapping(value="/fileUpload")
    public R fileUpload(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException {
        // 这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断路径是否存在,不存在会自动创建
        String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/static/upload");
        // 上传文件的原名(即上传前的文件名字)
        String newFileName = null;
        List<String> urlList = new ArrayList<>();
        for (MultipartFile myfile : myfiles) {
            if (myfile.isEmpty()) {
                return null;
            } else {
                byte[] bytes = ThumbnailsUtil.autoSize(myfile.getInputStream(), 120, 80);
                qiniuCloudStorageService.upload(bytes);
                // 单独完成一个服务器用于保管图片,(1)可以使用java,(2)分布式文件存储FastDFS
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                String strDate = format.format(new Date());
                newFileName = strDate +
                        BaseUtil.acceptRandom(BaseUtil.NUMBER_CONTENT, 6) + "." +
                        BaseUtil.acceptFileType(myfile.getOriginalFilename());
                try {
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, newFileName));
                    String url = pro.getBaseVisitURL() + "upload/" + newFileName;
                    urlList.add(url);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return R.ok().put("errno", 0).put("data", urlList);
    }
}
